package com.cci.kangdao.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * @author William Du
 * @date 2019/7/18
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private final static Log log = LogFactory.getLog(ApplicationContextUtils.class);

    private static org.springframework.context.ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext arg0) throws BeansException {
        if (applicationContext == null) {
            applicationContext = arg0;
        }
    }

    public static org.springframework.context.ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static String getProperties(String name) {
        return getApplicationContext().getEnvironment().getProperty(name);
    }

    public static InputStream getResource(String classPath) throws IOException {
        Resource resource = new ClassPathResource(classPath);
        return resource.getInputStream();
    }

    public static Object runMethod(String serviceName, String methodName, Object... params){
        try {
            Object service = getBean(serviceName);
            Class<? extends Object>[] paramClass = null;
            if (null != params) {
                int paramsLength = params.length;
                paramClass = new Class[paramsLength];
                for (int i = 0; i < paramsLength; i++) {
                    paramClass[i] = params[i].getClass();
                }
            }
            // 找到方法
            Method method = ReflectionUtils.findMethod(service.getClass(), methodName, paramClass);
            // 执行方法
            return ReflectionUtils.invokeMethod(method, service, params);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
           return null;
        }
    }

}
